<?php

namespace app\admin\controller;

use core\Controller;
use core\Request;
use core\Session;
use think\facade\Db;
use Gregwar\Captcha\CaptchaBuilder;

class Login extends Controller
{
    public function index(): void
    {
        $this->assign('title', "FAKE Framework");
        $this->fetch('index');
    }

    /**
     * 输出验证码图像
     */
    public function captcha()
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        Session::set('captcha', strtolower($builder->getPhrase()));

        // 获得验证码图片二进制数据
        $img_content = $builder->get();

        // 输出验证码二进制数据
        echo $img_content;
    }

    public function checkLogin(): void
    {
        $request = Request::instance();
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        $captcha = $request->post('captcha', '');

        if (($username == '') || ($password == '')) {
            $this->error('该用户名或密码不能为空', 'index');
        }

        if (strtolower($captcha) !== Session::get('captcha')) {
            //$this->error('输入的验证码不正确', 'index');
        }

        $infoAdmin = Db::name('admin')->where('username', $username)->find();
        if (empty($infoAdmin)) {
            $this->error('用户名不存在', 'index');
        }
        if ($infoAdmin['status'] != 1) {
            $this->error('密码错误', '账户被冻结');
        }
        if ($infoAdmin['password'] != md5EncryptionStr($password, $infoAdmin['salt'], $infoAdmin['id'])) {
            $this->error('密码错误', 'index');
        }

        //添加登录信息
        $data['admin_id'] = $infoAdmin['id'];
        $data['ip'] = $request->ip();
        $data['loginTime'] = time();
        Db::name('admin_login')->insert($data);

        //登录成功将信息保存到session中
        Session::set('username', $username);

        $this->success('登录成功', 'index/index');
    }

    public function outLogin()
    {
        Session::delete('username');
        Session::clear();

        //redirect('/admin/login/index');
        jsonApi(2,'退出成功',['url'=>url('login/index')]);
    }

}
